package m.store.action;

import com.alibaba.fastjson.JSONObject;
import m.base.action.BaseAction;
import m.base.util.LevelUtil;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.*;
import m.html.VueCollectResult;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.*;
import m.store.model.*;
import m.store.service.GoodsOutRecordService;
import m.store.util.ColorUtil;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.NumberUtil;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

@ActionMeta(name = "store/goodsOutRecord")
public class GoodsOutRecordAction extends BaseAction {
    private GoodsOutRecord model;
    @RequestMeta(logTitle = "出库明细",logDescription = "保存退货信息")
    public JSONMessage saveRefund() throws Exception {
        getService(GoodsOutRecordService.class).saveRefund(model);
        return new JSONMessage(0,"退货成功，记录生效");
    }
    @RequestMeta(logTitle = "出库明细",logDescription = "删除退货信息")
    public JSONMessage deleteRefund() throws Exception {
        getService(GoodsOutRecordService.class).deleteRefund(model.getOid());
        return new JSONMessage(0,"删除成功");
    }
    /*
     * 编辑undefined
     */
    public VueResult inputRefund() throws Exception {
        if(null!=model&&!ObjectUtil.isEmptyOid(model.getBackRecord())){
            model.setBackRecord(ModelQueryList.getModel(model.getBackRecord(),"*","goods.name"));
            model.setRecord(ModelQueryList.getModel(model.getRecord(),"*"));
            //model.setNum(model.getBackRecord().getSurplusNum());
            model.setPrice(model.getBackRecord().getPreferentialPrice());
            model.setPreferential(0d);
            model.setSaleAmount(0d);
        }else{
            throw new MException(this.getClass(),"参数错误");
        }
        ModelForm form = new ModelForm("录入退货");
        form.addItem(
            FormHtml.inputStyle("商品名称", "{{model.backRecord.goods.name}}").setSpan(3),
            FormHtml.inputStyle("数量", "{{formatNumber(model.backRecord.num,'#,##0')}}"),
            FormHtml.inputStyle("可退数量", "{{formatNumber(model.backRecord.surplusNum,'#,##0.00')}}"),
            FormInput.number("退货数量", "model.num").setPlaceholder("请输入退货数量").setRequired(true),
            FormHtml.inputStyle("单价", "{{formatNumber(model.backRecord.price,'#,##0.00')}}"),
            FormHtml.inputStyle("优惠单价", "{{formatNumber(model.backRecord.preferentialPrice,'#,##0.00')}}"),
            FormInput.number("退货单价", "model.price").setPlaceholder("请输入退货单价").setRequired(true),
            FormHtml.inputStyle("总优惠", "{{formatNumber(model.backRecord.preferential,'#,##0.00')}}"),
            FormHtml.inputStyle("金额", "{{formatNumber(model.backRecord.saleAmount,'#,##0.00')}}"),
            FormHtml.inputStyle("退货金额", "{{formatNumber(model.saleAmount,'#,##0.00')}}").setRequired(true),
            FormInput.textarea("退货备注","model.remark").setSpan(3).setPlaceholder("请输入退货备注")
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("确认退货","saveRefund").setConfirm("确定要退货吗？")
        )
        .addWatch("model.num","this.model.saleAmount=this.model.num*this.model.price;")
        .addWatch("model.price","this.model.saleAmount=this.model.num*this.model.price;")
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("saveRefund",actionUrl("saveRefund"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
    }
    /*
     * 出库商品列表
     */
    public VueResult recordList() throws Exception {
        boolean refund="refund".equals(getParamsValue("oper"));
        boolean isSale= !SaleInfo.Type_Refund.equals(getParamsValue("sale.type"));
        VueListResult result=getVueListResult(isSale?"出库明细":"退货明细",GoodsOutRecord.class,actionUrl("recordList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addQueryFields("surplusNum");
        result.addCol(toTextColumn("仓库", "record.repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        result.addCol(toTextColumn("类型", "record.goods.typeName", 100, true));
        result.addCol(toLinkColumn("商品名称", "record.goods.name", 200, true,
            new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                .addParam("oid","record.goods.oid")
        ));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle(isSale?"出库":"退货").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "num", 100, true).setGroupTitle(isSale?"出库":"退货"));
        result.addCol(toNumberColumn(isSale?"总优惠":"总扣减", "preferential", 100, true));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle(isSale?"销售":"退款").setCount(ListCount.NONE));
        result.addCol(toNumberColumn("金额", "saleAmount", 100, true).setGroupTitle(isSale?"销售":"退款"));
        result.addCol(toTextColumn("备注","remark",100,true));
        if(refund){
            result.addCol(toSpaceColumn("操作", 100,
                ListElement.test("record.surplusNum>0",
                    ListButton.modal("录入退货", ButtonType.WARN,actionUrl("inputRefund"),1000,SuccessMethod.REFRESH)
                        .addParam("model.backRecord.oid","oid").addParam("model.record.oid","record.oid")
                ),
                ListElement.test("record.num<0",
                    ListButton.ajax("删除退货", ButtonType.ERROR,actionUrl("deleteRefund"),SuccessMethod.REFRESH)
                        .addParam("model.oid","oid").setConfirm("确定要删除退货吗？")
                )
            ).setFixed(Align.RIGHT));
        }
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("sale.oid",getParamsValue("sale.oid")));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addOrder(QueryOrder.asc("oid"));
        return result;
    }
    /*
     * 出库商品列表
     */
    public VueResult refundRecordList() throws Exception {
        VueListResult result=getVueListResult("退货出库明细",GoodsOutRecord.class,actionUrl("refundRecordList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(toLinkColumn("出库单号", "sale.orderNo", 120, true,
            new ListEvent(actionUrl(SaleInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","sale.oid")
        ));
        result.addCol(toDateColumn("出库日期","sale.saleDate"));
        result.addCol(toTextColumn("仓库", "record.repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        result.addCol(toTextColumn("类型", "record.goods.typeName", 100, true));
        result.addCol(toLinkColumn("商品名称", "record.goods.name", 200, true,
            new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                .addParam("oid","record.goods.oid")
        ));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("退货").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "num", 100, true).setGroupTitle("退货"));
        result.addCol(toNumberColumn("总扣减", "preferential", 100, true));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("退款").setCount(ListCount.NONE));
        result.addCol(toNumberColumn("金额", "saleAmount", 100, true).setGroupTitle("退款"));
        result.addCol(toTextColumn("备注","remark",100,true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("sale.refundStock.oid",getParamsValue("sale.refundStock.oid")));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        result.addOrder(QueryOrder.asc("oid"));
        return result;
    }
    private ListColumn getTypeColumn(){
        String dict="m.store.model.SaleInfo!type";
        return toElementColumn("类型", "sale.type", 100,
            ListElement.tag(dict, ColorUtil.getSaleType(),false)
        ).setAlign(Align.CENTER).setFilter(true).setDictType(dict);
    }
    public VueResult selectRefundList() throws Exception {
        String selected=getParamsValue("selected","");
        VueListResult result=getVueListResult("选择出库明细",GoodsOutRecord.class,actionUrl("selectRefundList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addQueryFields("oid","goods.oid");
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("仓库", "record.repository.oid", 100, true).setDictType(RepositoryInfo.class,PowerUtil.getSessionStoreOid()));
        result.addCol(toTextColumn("类型", "goods.typeName", 100, true));
        result.addCol(toLinkColumn("商品名称", "goods.name", 200, true,
            new ListEvent("page/store/storeGoods.js", EventType.MODAL,600)
                .addParam("oid","goods.oid")
        ));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("出库").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "num", 100, true).setGroupTitle("出库"));
        result.addCol(toNumberColumn("总优惠", "preferential", 100, true).setGroupTitle("出库"));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 90, true).setGroupTitle("销售").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("可退", "surplusNum", 80, true).setGroupTitle("销售"));
        result.addCol(toSpaceColumn("操作", 100,
            ListElement.test("record.oid!='"+selected+"'",
                ListButton.back("选择", ButtonType.PRIMARY)
                    .addParam("","")
            ),
            ListElement.elseOther(ListElement.tag("已选",""))
        ).setFixed(Align.RIGHT));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("sale.oid",getParamsValue("sale.oid")));
        result.addCondition(QueryCondition.gt("surplusNum",0));
        result.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        return result;
    }

    /**
     * 商品、客户、台账
     */
    public VueResult goodsRecordList() throws Exception {
        VueListResult result=getVueListResult("出库商品明细台账",GoodsOutRecord.class,actionUrl("goodsRecordList"));
        result.setFunction(LevelUtil.exportFunc(),false);
        result.setHeight(-1);
        result.addCol(toIndexColumn());
        result.addCol(getTypeColumn());
        result.addCol(toLinkColumn("出库单号", "sale.orderNo", 120, true,
            new ListEvent(actionUrl(SaleInfoAction.class,"toView"), EventType.MODAL,1200)
                .addParam("model.oid","sale.oid")
        ));
        if(StringUtil.notSpace(getParamsValue("goodsOid"))) {
            result.hideHead();
            result.addCol(toTextColumn("出库客户", "sale.guest.name", 150, true));
            result.addCondition(QueryCondition.eq("goods.oid", getParamsValue("goodsOid")));
        }else if(StringUtil.notSpace(getParamsValue("guestOid"))){
            result.hideHead();
            result.addCol(toTextColumn("商品名称", "goods.name", 150, true));
            result.addCondition(QueryCondition.eq("sale.guest.oid", getParamsValue("guestOid")));
        }else{
            result.addCol(toTextColumn("出库客户", "sale.guest.name", 150, true));
            result.addCol(toTextColumn("商品名称", "goods.name", 150, true));
        }
        result.addCol(toDateColumn("出库日期", "sale.saleDate", 100, true));
        result.addCol(toNumberColumn("单价", "price", 100, true).setGroupTitle("出库").setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("数量", "num", 100, true).setGroupTitle("出库"));
        result.addCol(toNumberColumn("总优惠", "preferential", 100, true));
        result.addCol(toNumberColumn("单价", "preferentialPrice", 100, true).setGroupTitle("销售").setCount(ListCount.NONE));
        result.addCol(toNumberColumn("金额", "saleAmount", 100, true).setGroupTitle("销售"));
//        result.addCol(toIntegerColumn("数量", "refundNum", 100, true).setGroupTitle("退货"));
//        result.addCol(toNumberColumn("金额", "refundAmount", 100, true).setGroupTitle("退货"));
        result.addCol(toNumberColumn("入库单价", "stockPrice", 100, true));
        result.addCol(toNumberColumn("盈利金额", "gainAmount", 100, true));
        result.addCol(toIntegerColumn("数量", "surplusNum", 100, true).setGroupTitle("剩余"));
        result.addCol(toNumberColumn("金额", "surplusAmount", 100, true).setGroupTitle("剩余"));
        result.addCol(toTextColumn("备注","remark",100,true));
        result.addCol(toTextColumn("登记人", "sale.inputUser.realname", 100, true));
        result.addCol(toDateTimeColumn("录入时间", "sale.inputDate", 130, true));
        result.addCol(toTextColumn("审核人", "sale.checkUser.realname", 100, true));
        result.addCol(toDateTimeColumn("审核时间", "sale.checkDate", 130, true));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("sale.status", OrderModel.Status_Done));
        result.addCondition(QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()));
        result.addOrder(QueryOrder.asc("oid"));
        return result;
    }
    public VueResult goodsRecordCollect() throws Exception {
        FromQueryList from=FromQueryList.fromGroup("a",
            ModelQueryList.instance(GoodsOutRecord.class,new String[0],null,
                QueryCondition.and(
                    QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()),
                    QueryCondition.eq("sale.status",OrderModel.Status_Done)
                )
            )
        );
        from.addCondition("#{a.store.oid}=? and #{a.sale.status}=?",PowerUtil.getSessionStoreOid(),OrderModel.Status_Done);
        VueCollectResult result=getVueCollectResult("出库记录汇总",from,actionUrl("goodsRecordCollect"));
        result.setFunction(LevelUtil.exportFunc(),LevelUtil.chartFunc());
        result.setHeight(-1);
        result.addCol(collectIndexColumn());
        result.addCol(collectTextColumn("账期月份","DATE_FORMAT(#{a.sale.saleDate},'%Y-%m') saleMonth",100,true));
        result.addCol(collectElementColumn("出库类型","#{a.sale.type} saleType",100,
                ListElement.tag("m.store.model.SaleInfo!type", ColorUtil.getSaleType(),false)).setFilter(true).setDictOption(SaleInfo.class,"type"));
        result.addCol(collectDateColumn("出库日期","#{a.sale.saleDate} saleDate",100,true));
        result.addCol(collectTextColumn("进货客户","#{a.sale.guest.name} guestName",180,true));
        result.addCol(collectTextColumn("出库商品","#{a.goods.name} goodsName",200,true));
        result.addCol(collectIntegerColumn("出库数量","SUM(#{a.num}) saleNum",100,true));
        result.addCol(collectNumberColumn("总优惠","SUM(#{a.preferential}) preferential",100,true));
        result.addCol(collectNumberColumn("出库金额","SUM(#{a.saleAmount}) saleAmount",100,true));
        result.addCol(collectNumberColumn("盈利金额", "SUM(#{a.gainAmount}) gainAmount", 100, true));
        return result;
    }
    public GoodsOutRecord getModel() {
        return model;
    }

    public void setModel(GoodsOutRecord model) {
        this.model = model;
    }
}
